#include "IOwebGUI.h"

#if defined(ESP8266)
    ESP8266WebServer server(80);
    ESP8266WebServer* webGuiServer;
#elif defined(ESP32)
    WebServer server(80);
    WebServer* webGuiServer;
#endif

void handleNotFound() 
{
    String message = "File Not Found\n\n";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET) ? "GET" : "POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";

    for (uint8_t i = 0; i < server.args(); i++) 
    {
      message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }

    server.send(404, "text/plain", message);
}

void IOwebGUI::provideGUI() 
{
    server.send(200, "text/html", GUI);
}

void IOwebGUI::update(IOPoint* points [], int size)
{
    for (int i = 0; i < size; ++i)
    {
        points[i]->update();
    } 
    server.handleClient();
    delay(2);
}

void IOwebGUI::init(IOPoint* points [], int size)
{
    HTML = "\
        <html>\
            <head>\
              <title>ESP_Web_GUI</title>\
            </head>\
        <body style=\"background-color: #3e3e3e; Color: #ffffff;\" onload=\"setup()\">\
        <div style=\"width:1000px; clear:both;\">";
    
    for (int i = 0; i < size; ++i)
    {
        HTML += points[i]->HTML;
    }
    
    HTML += "\
        <div style=\"border:1px solid black; width:800px; float:left; margin-left: 30px;\">\
            <p>" + text + "</p>\
        </div>";
    
    HTML += "</div>\
            <script>\
                function setup() {";
    
    for (int i = 0; i < size; ++i)
    {
        HTML += points[i]->loopFunc;
    }
    
    HTML += "}";
            
    for (int i = 0; i < size; ++i)
    {
        HTML += points[i]->JS;
    }
    
    HTML += "\
            </script>\
        </body>\
    </html>";
    
    GUI = HTML.c_str();
    
    webGuiServer = &server;
    webGuiServer->on("/gui", [&]{provideGUI();});
    webGuiServer->onNotFound(handleNotFound);
    
    for (int i = 0; i < size; ++i)
    {
        points[i]->init();
    } 
    
    webGuiServer->begin();
}